#include "TgaLoader.h"

namespace GenBen {

// Loader code based on "Truevision TGA FILE FORMAT SPECIFICATION Version 2.0"

#pragma pack(1)

struct TgaHeader
{
	byte id_length;
	byte color_map_type;
	byte image_type;
	uint16 color_map_index;
	uint16 color_map_length;
	byte color_map_entry_size;
	uint16 x_origin;
	uint16 y_origin;
	uint16 width;
	uint16 height;
	byte pixel_depth;
	byte image_descriptor;
};

#pragma pack()


void loadTga(const string& path, uint& width, uint& height, void** data)
{
	ASSERT(sizeof(TgaHeader) == 18);

	FILE* file = fopen(path.c_str(), "rb");

	TgaHeader header;
	fread(&header, sizeof(TgaHeader), 1, file);

	ASSERT(header.color_map_type == 0);
	ASSERT(header.image_type == 2);
	ASSERT(header.pixel_depth == 32 || header.pixel_depth == 24);

	fseek(file, header.id_length, SEEK_CUR);

	byte* buffer = (byte*)malloc(header.width * header.height * 4);
	if(header.pixel_depth == 24)
	{
		for(int pixel = 0; pixel < (header.width * header.height); ++pixel)
		{
			byte color[3];
			fread(color, 3, 1, file);
			
			buffer[pixel * 4] = color[2];
			buffer[pixel * 4 + 1] = color[1];
			buffer[pixel * 4 + 2] = color[0];
			buffer[pixel * 4 + 3] = 0xFF;
		}
	}
	else
	{
		for(int pixel = 0; pixel < (header.width * header.height); ++pixel)
		{
			byte color[4];
			fread(color, 4, 1, file);
			
			buffer[pixel * 4] = color[2];
			buffer[pixel * 4 + 1] = color[1];
			buffer[pixel * 4 + 2] = color[0];
			buffer[pixel * 4 + 3] = color[3];
		}
	}

	*data = (void*)buffer;
	width = header.width;
	height = header.height;

	fclose(file);
}

}